package com.bshinfo.web.base.util;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

/**
 * IP地址、主机名称获取工具类<br/>
 * 
 * 功能描述: 获取机器的IP地址,主机名称<BR/>
 * 
 * < <BR />
 * 	 1. 获取IP地址 <BR/>
 *   2. 获取主机名称<BR/>
 *   3. 获取请求的IP地址(需要HttpServletRequest对象)<BR/>
 * >
 * 
 * 
 * @author 	[zhangChao]
 * 
 * @see 	[java.net.InetAddress]
 * 
 * @since 	[JDK 1.7] 
 * 
 * @version [1.0]
 * 
 * @Date    [2016-12-16 15:21:51]
 */
public class IPAddressUtil 
{
	// 本地日志异常记录
	private static final Logger logger = Logger.getLogger(IPAddressUtil.class );
	
	// 构造方法
	public IPAddressUtil() 
	{
		
	}

	/**
     * 获取当前主机的网络地址<br/>
     * 
     * @return  { java.net.InetAddress}  [当前主机的网络地址,异常时返回-null]
     * 
     * @author 	[zhangChao]
     * 
     * @Date    [2016-12-16 15:21:51]
     */
	public static InetAddress getInetAddress()
	{  
        try
        {  
            return InetAddress.getLocalHost();  
        }
        catch(UnknownHostException e)
        {  
        	logger.error("unknown host!",e);
        }  
        
        return null;  
    }  
	
	/**
     * 获取当前主机的IP地址<br/>
     * 
     * @return  {String}  [当前主机的IP地址,参数为空时返回-null]
     * 
     * @author 	[zhangChao]
     * 
     * @Date    [2016-12-16 15:21:51]
     */
	public static String getHostIp(InetAddress netAddress)
	{  
        if(null == netAddress)
        {  
            return null;  
        }  
        
        //get the ip address 
        String ip = netAddress.getHostAddress();
        
        return ip;  
    }  
  
	
	/**
     * 获取当前主机的名称<br/>
     * 
     * @return  {String}  [当前主机的名称,参数为空时返回-null]
     * 
     * @author 	[zhangChao]
     * 
     * @Date    [2016-12-16 15:21:51]
     */
    public static String getHostName(InetAddress netAddress)
    {  
        if(null == netAddress)
        {  
            return null;  
        }  
        //get the host address
        String name = netAddress.getHostName();  
        return name;  
    }  
    
    
	/**
     * 获取请求主机的IP地址<br/>
     * 
     * @return  {String}  [当前主机的名称,参数为空时返回-null]
     * 
     * @author 	[zhangChao]
     * 
     * @Date    [2016-12-16 15:21:51]
     */
    public static String getRemoteIpAddress(HttpServletRequest request)
    {
    	 if(null == request)
         {  
             return null;  
         }  
         //get the host address
         String name = request.getRemoteAddr();  
         return name;  
    }
    
    public static void main(String[] args) {
		System.out.println(UUID.randomUUID().toString().replaceAll("-", ""));
	}
}
